package com.hush.springcloud.controller;

import com.hush.springcloud.pojo.Dept;
import com.hush.springcloud.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 周宇
 * @create 2020-11-22 17:04
 */
//提供 Restful 服务！
@RestController //@RestController 相当于 @Controller 加 @ResponseBody
public class DeptController {

    //required = false 表示忽略当前要注入的bean，如果有直接注入，没有跳过，不会报错
    @Autowired
    private DeptService service;

    //org.springframework.cloud.client.discovery.DiscoveryClient
    @Autowired
    private DiscoveryClient client;

    //@RequestBody
    //如果参数是放在请求体中，传入后台的话，那么后台要用@RequestBody才能接收到
    @PostMapping("/dept/add")
    public boolean addDept(@RequestBody Dept dept) {
        return service.addDept(dept);
    }

    @GetMapping("/dept/get/{id}")
    public Dept get(@PathVariable("id") Long id) {
        return service.queryById(id);
    }

    @GetMapping("/dept/list")
    public List<Dept> queryAll() {
        return service.queryAll();
    }

    //注册进来的微服务~,获取一些信息~
    @GetMapping("/dept/discovery")
    public Object discovery() {
        //获得微服务列表清单
        List<String> list = client.getServices();
        System.out.println("client.getServices()==>" + list);

        //得到一个具体的微服务！
        List<ServiceInstance> serviceInstanceList = client.getInstances("SPRINGCLOUD-PROVIDER-DEPT");
        //ServiceInstance服务的实体
        for (ServiceInstance serviceInstance : serviceInstanceList) {
            System.out.println(
                    serviceInstance.getServiceId() + "\t" +
                            serviceInstance.getHost() + "\t" +
                            serviceInstance.getPort() + "\t" +
                            serviceInstance.getUri());
        }
        return this.client;
    }
}
